package com.sites.cds.common.directive;

import java.util.List;

import com.jfinal.aop.Aop;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.TemplateException;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;
import com.sites.common.model.Files;

/**
 * 文章附件获取指令
 * 
 * #afld(String files) 接受一个String类型的filesId参数，files可能是一个值也可能是多个值
 * 		<img src="">
 * #end
 * 
 * #afld(String files, String paraName) 还可以接受一个String类型的paraName参数
 * 		<img src="">
 * #end
 * 
 * @author zyg
 * 2020年9月22日 下午9:02:29
 */
public class ArticleFilesListDirective extends Directive {

	private Expr filesExpr;//第一个参数表达式
	private Expr paraNameExpr;//第二个参数表达式
	private int paraNum;//参数个数
	private String paraNameValue = "file";
	
	private DirectiveService srv = Aop.get(DirectiveService.class);
	
	@Override
	public void setExprList(ExprList exprList) {
		paraNum = exprList.length();
		if(paraNum < 1 || paraNum > 2){
			//参数不对应时抛出异常，该异常是词法、语法异常
			throw new ParseException("参数个数异常",location);
		}
		filesExpr = exprList.getExpr(0);
		if(paraNum == 2){
			paraNameExpr = exprList.getExpr(1);
		}
	}
	
	@Override
	public void exec(Env env, Scope scope, Writer writer) {
		String filesStr = "";
		
		Object filesObject = filesExpr.eval(scope);
		if(filesObject instanceof String){
			filesStr = (String) filesObject;
		} else {
			throw new TemplateException("第一个参数必须是String类型", location);
		}
		
		if(paraNum == 2){
			Object paraNameObject = paraNameExpr.eval(scope);
			if(paraNameObject instanceof String){
				paraNameValue = (String) paraNameObject;
			} else {
				throw new TemplateException("第二个参数必须是String类型", location);
			}
		}
		
		// 查询数据库
		List<Files> filesList = srv.getFilesByIds(filesStr);
		for(Files files : filesList){
			scope.set(paraNameValue, files);
			stat.exec(env, scope, writer);
		}
	}

	
	@Override
	public boolean hasEnd() {
		return true;
	}
}
